/*
 * Copyright 2013 Sebastian Gesemann <s.gesemann@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This header contains a little helper class that conveniently wraps
 * a pointer and an integer (size) for referencing some array. It
 * automatically converts from raw arrays and std::vectors like you
 * would expect from a reference-like type for arrays.
 */

#ifndef ARRAY_REF_HPP_INCLUDED
#define ARRAY_REF_HPP_INCLUDED

#include <cassert>
#include <cstddef>
#include <vector>
#include <type_traits>

namespace sg {

// helper class for constraining the templates below
template<class T, class U, class Ret=void>
struct enable_if_array_ref_assignable
: std::enable_if<
	std::is_convertible<U*,T*>::value && sizeof(T)==sizeof(U),
	Ret
  >
{};

/// simple proxy type that acts as a reference to a linear array
template<class T>
class array_ref
{
public:
	array_ref()
	: base_(0), size_(0)
	{}

	array_ref(T* p, std::size_t s)
	: base_(p), size_(s)
	{}

	template<class U>
	array_ref(array_ref<U> const& r
		,typename enable_if_array_ref_assignable<T,U>::type* =0)
	: base_(r.get()), size_(r.size())
	{}

	template<class U, std::size_t N>
	array_ref(U (&r)[N]
		,typename enable_if_array_ref_assignable<T,U>::type* =0)
	: base_(r), size_(N)
	{}
		
	template<class U>
	array_ref(std::vector<U> & v
		,typename enable_if_array_ref_assignable<T,U>::type* =0)
	: base_(v.empty()?0:&v[0]), size_(v.size())
	{}

	template<class U>
	array_ref(std::vector<U> const& v
		,typename enable_if_array_ref_assignable<T,const U>::type* =0)
	: base_(v.empty()?0:&v[0]), size_(v.size())
	{}

	T* get() const {return base_;}
	std::size_t size() const {return size_;}
	bool empty() const {return size_==0;}

	T& operator[](std::size_t index) const
	{
		assert(index<size_);
		return base_[index];
	}

	T* begin() const {return base_;}
	T* end() const {return size_?base_+size_:base_;}

private:
	T* base_;
	std::size_t size_;
};

template<class T>
inline array_ref<T> slice(array_ref<T> tmp, std::size_t beg, std::size_t end)
{
	assert(beg <= end);
	assert(end <= tmp.size());
	return array_ref<T>(tmp.get()+beg,end-beg);
}

} // namespace sg

#endif

